# coding=utf-8
# -*- coding: utf-8 -*-

import re
import os
import requests
import json
import re
from sklearn.cluster import KMeans
import numpy as np
from matplotlib import pyplot as plt
import csv
from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong']  # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

data_file_name = "sina_bifa.csv"
data = np.genfromtxt(data_file_name, delimiter=',')


# print(data[0:2, 13:16])

def kmeans_test2():
    num_clusters = 2
    X = data[:, [13, 15]]  # 欧赔胜负
    S = data[:, 6]
    # for i in range(len(X)):
    #     print(X[i])
    clf = KMeans(n_clusters=num_clusters, n_init=1, verbose=1)
    clf.fit(X)
    right_count = 0

    Y = []
    with open(data_file_name, 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for row in reader:
            ss = row[6].split(':')
            Y.append(int(ss[0]) - int(ss[1]))
            # if int(ss[0]) > int(ss[1]):
            #     Y.append(1)
            # elif int(ss[0]) == int(ss[1]):
            #     Y.append(0)
            # else:
            #     Y.append(-1)
    win = {}
    draw = {}
    lose = {}
    M = {}  # ['0':{'-8':0,'2':1002},'1':{}...]
    for i in range(len(clf.labels_)):
        label = "%d" % int(clf.labels_[i])  # 分类
        ball = "%d" % int(Y[i])  # 净胜球
        if label not in M:
            M[label] = {}
        if ball in M[label]:
            M[label][ball] += 1
        else:
            M[label][ball] = 1

    print(M)
    # 创建子图
    for i in range(num_clusters):
        plt.subplot(341 + i)
        # 在第一张子图上绘制两个图形
        # x,y1的散点图，黑色方块
        # xfit,fit(xfit)红色实线，线宽为2
        # plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2)
        # 设置x轴范围：2到20
        # 设置y轴范围：2到14
        dx = []
        dy = []
        clus = str(i)
        for k in M[clus]:
            dx.append(int(k))
            dy.append(M[clus][k])
        plt.title('分类%d' % i)
        plt.bar(dx, dy, color='b', width=.3, alpha=0.6, label='分类%d' % i, align="center")
        plt.xlabel('净胜球数')
        plt.ylabel('出现次数')
        plt.axis([-7, 7, 0, 1500])
    plt.show()


def kmeans_test1():
    X = data[:, 13]  # 欧赔胜负
    y = data[:, 15]  # 欧赔胜负
    for i in range(len(X)):
        print('%d,%d' % (X[i], y[i]))
    # x = np.arange(-5.0, 5.0, 0.02)
    # y1 = np.sin(x)
    # print(x)
    # print(y1)
    # plt.plot(x, y1, 'ro')
    plt.plot(X, y, 'ro')
    plt.show()


if __name__ == '__main__':
    kmeans_test1()
# print(win)
# for i in range(len(S)):

# ss = S[i].split(':')
#     if int(ss[0]) > int(ss[1]):
#         Y.append(1)
#     elif int(ss[0]) == int(ss[1]):
#         Y.append(0)
#     else:
#         Y.append(-1)
# plt.scatter(Y, clf.labels_, c=clf.labels_)
# plt.show()
# 指定用户0与用户5作为初始化聚类中心
# init = np.vstack([ x[0], x[5] ])
# clf = KMeans(n_clusters=2, init=init)
# clf.fit(x)
# print(clf.labels_)
'''
    文件格式
    0开赛时间，1足彩期号，2场次，3联赛，4主场，5客场，6比分，7必发胜,8平,9负,10必发指数胜,11平,12负,13百家欧赔胜,14平,15负
    '''
